#Testing the module's limits with an implementation of War
import Game, sys, socket

#Initialize the socket
hostSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#Bind the socket to a port, depending on whether or not a port is passed command line
if len(sys.argv) == 1:
    hostSocket.bind(('',2000))
else:
    hostSocket.bind(('',int(sys.argv[1])))

#Wait for a call from a client
hostSocket.listen(1)
connection,address = hostSocket.accept()

d = Game.PokerDeck
d.shuffle()

#Configure the board to have two play spaces for the two players
playSpace = Game.Board('one','two')

#Initialize the players
(player1,player2) = Game.initPlayers(2,playSpace,['deck'],['playLoc'])
for x in (player1,player2): x.addItems(d.draw(13))
player1.setName("Player 1")
player1.setValue('playLoc','one')
player2.setName("Player 2")
player2.setValue('playLoc','two')

#Constants for the rest of the code have been initialized
    
def hasLost(Player):
    return len(Player.possessions['deck']) == 0

def play(Player):
    #Print and send the output
    out = str(Player) + " plays " + str(Player.possessions['deck'][0]) + "!"
    print(out)
    connection.send("t" + out)
    #Actually play the card
    Player.play(Player.possessions['deck'][0],Player.getValue('playLoc'))

#Each player plays three cards, for a war
def warPlay():
    for x in range(3):
        if not hasLost(player1):
            prompt(player1)
            play(player1)
        if not hasLost(player2):
            prompt(player2)
            play(player2)

def takeCards(Player):
    #Print and send the message
    out = str(Player) + " wins the round!"
    print(out)
    connection.send("t" + out)
    #Perform the card removals
    Player.takeAll('one')
    Player.takeAll('two')

#Returns 0 if it is a tie, None otherwise
#Compares the top values and awards all the spoils to the winner, if there is one
def compareAndAward():
    #Compare each way, if neither comparison is satisfied, the cards are equal and a war begins
    if playSpace.contents('one')[-1].value > playSpace.contents('two')[-1].value: takeCards(player1)
    elif playSpace.contents('two')[-1].value > playSpace.contents('one')[-1].value: takeCards(player2)
    else: return 0

def prompt(Player):
    if Player == player1:
        print("Player 1, press enter")
        raw_input()
    else:
        #Send a request for input
        connection.send("pPlayer 2, press enter")
        #Wait for input from the other end
        connection.recv(1000)

tie = False
while not hasLost(player1) and not hasLost(player2):
    prompt(player1)
    prompt(player2)
    play(player1)
    play(player2)
    #Compare the cards, if it is a tie, a war begins
    if compareAndAward() == 0:
        out = "A war begins!"
        #Print and send the message
        print(out)
        connection.send("t" + out)
        #While the last card in the play spaces are equal, continue the war by laying down three cards at a time
        while compareAndAward() == 0 and not tie:
            warPlay()
            #If the war stale-mates in a tie, the whole game is a tie
            if hasLost(player1) and hasLost(player2) and compareAndAward() == 0:
                #Print and send that it's a tie
                out = "It's a tie!\n"
                print(out)
                connection.send("t" + out)
                tie = True
#The output
out = ''
#Set the output to be the winner
if hasLost(player1): out = "Player 2 wins the game!\n"
else: out = "Player 1 wins the game!\n"

#Print and send the output
print(out)
connection.send("t" + out)

#Close the connection
connection.close()